package com.means.polymerize.common.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.means.polymerize.common.constants.Global;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 参数转换工具
 *
 * @author xuhaifeng
 * @date 2020.2.9 上午 11:58
 */
@Slf4j
@SuppressWarnings("unused")
public class ParameterUtil {

    /**
     * 解析 JSON 参数
     * Gets body json str by json.
     *
     * @param request the request
     * @return the body json str by json
     */
    public static String getParameterByJson(HttpServletRequest request) {
        String line;
        final StringBuilder json = new StringBuilder();
        try {
            final BufferedReader reader = request.getReader();
            while (Objects.nonNull(line = reader.readLine())) {
                json.append(line);
            }
            if (StrUtil.isEmpty(json.toString())) {
                return Global.BRACES;
            }
            return json.toString();
        } catch (Exception e) {
            return Global.BRACES;
        } finally {
            log.info("========================== 接收参数：\n" + json);
        }
    }

    /**
     * Gets parameter by form data.
     *
     * @param request the request
     * @return the parameter by form data
     */
    public static JSONObject getParameterByFormData(HttpServletRequest request) {
        final JSONObject parameterObject = new JSONObject();
        final Set<Map.Entry<String, String[]>> entries = request.getParameterMap().entrySet();
        if (entries.size() != 0) {
            entries.stream().filter(entry -> !Global.FILE.equals(entry.getKey()))
                    .filter(entry -> Objects.nonNull(entry.getValue()) && entry.getValue().length != 0)
                    .forEach(entry -> parameterObject.put(entry.getKey(), entry.getValue()[0]));
        }
        log.info(String.format("========================== 接收参数：\n%s", parameterObject.toJSONString()));
        return parameterObject;
    }

    /**
     * 拉取请求头信息
     *
     * @param request the request
     * @return header map
     */
    public static Map<String, String> getHeaderMap(HttpServletRequest request) {
        final Map<String, String> map = new HashMap<>(50);
        try {
            final Enumeration<String> paramNames = request.getHeaderNames();
            request.setCharacterEncoding("UTF-8");
            while (paramNames.hasMoreElements()) {
                final String key = paramNames.nextElement();
                final String value = request.getHeader(key);
                if (StrUtil.equals(request.getMethod(), Global.GET)) {
                    map.put(key, new String(value.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
                } else {
                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        return map;
    }

    /**
     * 将一个request请求所携带的参数封装成map返回 ，带集合的
     *
     * @param request the request
     * @return params map
     */
    public static Map<String, Object> getParamsMap(HttpServletRequest request) {
        final Map<String, Object> map = new HashMap<>(50);
        final Map<String, String[]> parameterMap = request.getParameterMap();
        parameterMap.keySet().forEach(key -> {
            try {
                final String[] values = parameterMap.get(key);
                if (values.length == 1) {
                    map.put(key, values[0]);
                } else {
                    final List<String> list = new ArrayList<>();
                    Collections.addAll(list, values);
                    map.put(key, list);
                }
            } catch (Exception e) {
                log.info(e.getMessage());
            }
        });
        return map;
    }

}
